<?php

namespace App\Http\Controllers\Insure;

use App\Http\Controllers\Controller;
use App\Imports\Gas\GasImport;
use App\Models\Bus\Bus;
use App\Models\Dict;
use App\Models\Insure\Insure;
use App\Models\Insure\InsureFile;
use App\User;
use Carbon\Carbon;
use Illuminate\Database\Query\Builder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;

class InsureController extends Controller
{
    /**
     * 保险列表
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function insureList(Request $request)
    {
        $params = $request->all();
        $data = $this->getInsureList($params)->get()->toArray();
        if ($data) {
            $data = $this->transData($data);
        }

        return response()->formatJson(['personnel' => $data]);
    }

    public function getInsureList($params): Builder
    {
        $query = DB::table('akbus_insure as i')
            ->leftJoin('akbus_bus as b', 'i.bus_id', '=', 'b.id')
            ->select(
                'i.id',
                'b.license_plate_num',
                'b.type',
                'b.engine_num',
                'b.frame_nun',
                'b.max_num',
                'i.merc_company',
                'i.merc_money',
                'i.merc_time',
                'i.merc_start_date',
                'i.merc_end_date',
                'i.force_time',
                'i.force_money',
                'i.force_start_date',
                'i.force_end_date',
                'i.liability_money',
                'i.liability_seat_num',
                'i.liability_time',
                'i.liability_start_date',
                'i.liability_end_date',
                'i.created_at'
            );
        if (isset($params['license_plate_num'])) {
            $query
                ->where('b.license_plate_num', 'like', '%'.$params['license_plate_num'].'%');
        }

        return $query->orderByDesc('created_at');
    }

    public function transData($data)
    {
        $type = [
            '燃气车',
            '纯电动',
        ];
        foreach ($data as $key => $v) {
            $data[$key]['license_plate_num'] = '陕G'.$v['license_plate_num'];
            $data[$key]['type'] = $v['type'] !== null ? $type[$v['type']] : '-';
        }
        return $data;
    }

    /**
     * 获取数据字典
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function dictData(Request $request)
    {
        $params = $request->all();

        $result = Dict::getOptionsArrByName($params['title']);

        return response()->formatJson(['result' => $result]);
    }

    /**
     * 获取保险详情
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function insureInfo(Request $request)
    {
        $params = $request->all();
        $data = DB::table('akbus_insure as i')
            ->leftJoin('akbus_bus as b', 'i.bus_id', '=', 'b.id')
            ->select(
                'i.id',
                'i.bus_id',
                'b.license_plate_num',
                'b.type',
                'b.engine_num',
                'b.frame_nun',
                'b.max_num',
                'i.merc_company',
                'i.merc_money',
                'i.merc_time',
                'i.merc_start_date',
                'i.merc_end_date',
                'i.force_time',
                'i.force_money',
                'i.force_start_date',
                'i.force_end_date',
                'i.liability_money',
                'i.liability_seat_num',
                'i.liability_time',
                'i.liability_start_date',
                'i.liability_end_date',
                'i.created_at'
            )
            ->where('i.id', $params['id'])
            ->first();
        $data['license_plate_num'] = $data['bus_id'];

        $type = [
            '燃气车',
            '纯电动',
        ];
        $data['type'] = $type[$data['type']];

        $insure = Insure::query()->with('file')->find($data['id'])->toArray();

        $users = User::all();
        if (isset($insure['file']) && $insure['file'] !== []) {
            foreach ($insure['file'] as $k => $file) {
                $userName = $users->where('id', $file['user_id'])->first()->name;
                $data['files'][$k] = $file;
                $data['files'][$k]['userName'] = $userName;
            }
        } else {
            $data['files'] = [];
        }

        return response()->formatJson(['result' => $data]);
    }

    /**
     * 添加保险
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function addInsure(Request $request)
    {
        $params = $request->all();
        if (isset($params['license_plate_num'])) {
            $params['bus_id'] = $params['license_plate_num'];
        }
        $params['created_at'] = Carbon::now();
        unset(
            $params['id'],
            $params['type'],
            $params['engine_num'],
            $params['frame_nun'],
            $params['max_num'],
            $params['license_plate_num']
        );

        $insure = new Insure($params);
        $result = $insure->save();
        $message = $result ? '保存成功' : '保存失败';

        // 关联资质文件
        if (! empty($params['files'])) {
            foreach ($params['files'] as $work) {
                $work['type'] = 'insure';
                $file = new InsureFile($work);
                $insure->file()->save($file);
            }
        }
        return response()->formatJson(['result' => $result], $message);
    }

    /**
     * 编辑保险
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function editInsure(Request $request)
    {
        $params = $request->all();
        if (isset($params['license_plate_num'])) {
            $params['bus_id'] = $params['license_plate_num'];
        }
        $id = $params['id'];
        $params['updated_at'] = Carbon::now();
        unset(
            $params['id'],
            $params['type'],
            $params['engine_num'],
            $params['frame_nun'],
            $params['max_num'],
            $params['license_plate_num']
        );

        $insure = Insure::query()->find($id);
        $result = $insure->update($params);
        $message = $result ? '修改成功' : '修改失败';

        // 关联资质文件
        if (! empty($params['files'])) {
            foreach ($params['files'] as $work) {
                if (! array_key_exists('type', $work)) {
                    $work['type'] = 'insure';
                    $file = new InsureFile($work);
                    $insure->file()->save($file);
                }
            }
        }

        return response()->formatJson(['result' => $result], $message);
    }

    /**
     * 删除保险
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function delInsure(Request $request)
    {
        $result = false;
        if ($request->has('ids')) {
            $ids = explode(',', $request['ids']);
            $delCount = Insure::destroy($ids);
            $result = $delCount !== 0;
        }

        $message = $result ? '删除成功' : '删除失败';

        return response()->formatJson($result, $message);
    }

    /**
     * 导入加气记录
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function importInsure(Request $request)
    {
        $urlParse = parse_url($request->input('url'));
        $excelData = Excel::toArray(new GasImport, public_path().$urlParse['path']);
        $fullData = $excelData[0];

        // 删除前两行
        array_shift($fullData);
        array_shift($fullData);

        $data = [];
        $fields = [
            'license_plate_num',
            'force_money',
            'force_time',
            'force_start_date',
            'force_end_date',
            'merc_time',
            'merc_start_date',
            'merc_end_date',
            'merc_money',
            'merc_company',
            'liability_money',
            'liability_seat_num',
            'liability_time',
            'liability_start_date',
            'liability_end_date',
        ];
        $licensePlateNum = Bus::all()->pluck('license_plate_num', 'id')->toArray();
        // 整理数据，填充合并的单元格数据
        foreach ($fullData as $row) {
            $item = [];
            foreach ($fields as $index => $field) {
                $item[$field] = $row[$index];
            }
            $item['bus_id'] = array_search($item['license_plate_num'], $licensePlateNum, true);
            unset($item['license_plate_num']);

            if (is_int($item['force_time'])) {
                $item['force_time'] = $this->transformDateTime($item['force_time']);
            }
            if (is_int($item['force_start_date'])) {
                $item['force_start_date'] = $this->transformDateTime($item['force_start_date']);
            }
            if (is_int($item['force_end_date'])) {
                $item['force_end_date'] = $this->transformDateTime($item['force_end_date']);
            }
            if (is_int($item['merc_start_date'])) {
                $item['merc_start_date'] = $this->transformDateTime($item['merc_start_date']);
            }
            if (is_int($item['merc_end_date'])) {
                $item['merc_end_date'] = $this->transformDateTime($item['merc_end_date']);
            }
            if (is_int($item['merc_time'])) {
                $item['merc_time'] = $this->transformDateTime($item['merc_time']);
            }
            if (is_int($item['liability_time'])) {
                $item['liability_time'] = $this->transformDateTime($item['liability_time']);
            }
            if (is_int($item['liability_start_date'])) {
                $item['liability_start_date'] = $this->transformDateTime($item['liability_start_date']);
            }
            if (is_int($item['liability_end_date'])) {
                $item['liability_end_date'] = $this->transformDateTime($item['liability_end_date']);
            }

            $item['created_at'] = Carbon::now();
            $data[] = $item;
        }

        return response()->formatJson(Insure::query()->insert($data), '导入成功');
    }

    public function transformDateTime($intDate)
    {
        $date = $intDate - 25569;
        $time = $date * 24 * 60 * 60;

        return date('Y-m-d', $time);
    }
}
